package cn.tedu.sp02itemservice.controller;

import cn.tedu.entity.Item;
import cn.tedu.service.ItemService;
import cn.tedu.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@Slf4j
@RestController
public class ItemController {
    @Autowired
    private ItemService itemService;

    //特殊情况
    //http://localhost:8001/favicon.ico

    //http://localhost:8001/5
    //@PathVariable 接受get请求的协议头部分
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {

        log.warn("查询商品"+orderId);
        List<Item> items = itemService.getItems(orderId);

        //随机的阻塞代码，90%概率执行阻塞代码
        if (Math.random() < 0.8) {
            int t = new Random().nextInt(5000);
            log.warn("暂停"+t);
            Thread.sleep(t);
        }

        //return JsonResult.ok(items).msg("port="+port);
        return JsonResult.build().code(200).data(items);
    }

    //http://localhost:8001/5/[{"id": 1,"name": "abc","number": 23},{"id": 2,"name": "def","number": 11}]
    //@RequestBody 接受post请求的协议体部分
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items) {
        log.warn("decreaseNumber参数="+items);

        itemService.decreaseNumbers(items);
        return JsonResult.build().code(200).msg("减少库存成功");
    }

    @GetMapping("/favicon.ico")
    public void ico(){
    }
}
